{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import json\n",
    "\n",
    "import requests\n",
    "from autogen_agentchat.agents import AssistantAgent\n",
    "from autogen_core.models import UserMessage\n",
    "from autogen_ext.models.azure import AzureAIChatCompletionClient\n",
    "from azure.core.credentials import AzureKeyCredential\n",
    "from autogen_core import CancellationToken\n",
    "from autogen_core.tools import FunctionTool\n",
    "from autogen_agentchat.messages import TextMessage\n",
    "from autogen_agentchat.ui import Console\n",
    "from typing import Any, Callable, Set, Dict, List, Optional"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "finish_reason='stop' content='The capital of France is Paris.' usage=RequestUsage(prompt_tokens=14, completion_tokens=7) cached=False logprobs=None thought=None\n"
     ]
    }
   ],
   "source": [
    "client = AzureAIChatCompletionClient(\n",
    "    model=\"gpt-4o-mini\",\n",
    "    endpoint=\"https://models.inference.ai.azure.com\",\n",
    "    # To authenticate with the model you will need to generate a personal access token (PAT) in your GitHub settings.\n",
    "    # Create your PAT token by following instructions here: https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens\n",
    "    credential=AzureKeyCredential(os.environ[\"GITHUB_TOKEN\"]),\n",
    "    model_info={\n",
    "        \"json_output\": True,\n",
    "        \"function_calling\": True,\n",
    "        \"vision\": True,\n",
    "        \"family\": \"unknown\",\n",
    "    },\n",
    ")\n",
    "\n",
    "result = await client.create([UserMessage(content=\"What is the capital of France?\", source=\"user\")])\n",
    "print(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Dict, List, Optional\n",
    "\n",
    "\n",
    "def get_weather(city: str = \"new york\") -> Optional[Dict]:\n",
    "    \"\"\"\n",
    "    Fetches weather forecast from Tomorrow.io API\n",
    "    \n",
    "    Args:\n",
    "        city (str): City name for weather forecast (default: \"new york\")\n",
    "        \n",
    "    Returns:\n",
    "        Dict containing weather data or None if the request fails\n",
    "    \"\"\"\n",
    "    # URL encode the city name\n",
    "    encoded_city = requests.utils.quote(city)\n",
    "    url = f\"https://api.tomorrow.io/v4/weather/realtime?location={encoded_city}&apikey=5RXcTkDdWgQjHr8Ot9sLwQWtGQLfe4RM\"\n",
    "\n",
    "    headers = {\n",
    "        \"accept\": \"application/json\",\n",
    "        \"accept-encoding\": \"deflate, gzip, br\"\n",
    "    }\n",
    "\n",
    "    try:\n",
    "        response = requests.get(url, headers=headers)\n",
    "        response.raise_for_status()\n",
    "        return response.json()\n",
    "    except requests.RequestException as e:\n",
    "        print(f\"Error fetching weather data: {e}\")\n",
    "        return None\n",
    "    except json.JSONDecodeError as e:\n",
    "        print(f\"Error decoding JSON response: {e}\")\n",
    "        return None"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def vacation_destinations(city: str) -> tuple[str, str]:\n",
    "    \"\"\"\n",
    "    Checks if a specific vacation destination is available\n",
    "    \n",
    "    Args:\n",
    "        city (str): Name of the city to check\n",
    "        \n",
    "    Returns:\n",
    "        tuple: Contains city name and availability status ('Available' or 'Unavailable')\n",
    "    \"\"\"\n",
    "    destinations = {\n",
    "        \"Barcelona\": \"Available\",\n",
    "        \"Tokyo\": \"Unavailable\",\n",
    "        \"Cape Town\": \"Available\",\n",
    "        \"Vancouver\": \"Available\",\n",
    "        \"Dubai\": \"Unavailable\",\n",
    "    }\n",
    "\n",
    "    if city in destinations:\n",
    "        return city, destinations[city]\n",
    "    else:\n",
    "        return city, \"City not found\"\n",
    "\n",
    "# Example usage:\n",
    "# city, status = vacation_destinations(\"Barcelona\")\n",
    "# print(f\"How about visiting {city}? It's currently {status} there!\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "get_vacations = FunctionTool(\n",
    "    vacation_destinations, description=\"Search for vacation destinations and if they are availabe or not.\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [],
   "source": [
    "agent = AssistantAgent(\n",
    "    name=\"assistant\",\n",
    "    model_client=client,\n",
    "    tools=[get_vacations],\n",
    "    system_message=\"You are a travel agent that helps users find vacation destinations.\",\n",
    "    reflect_on_tool_use=True,\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ToolCallRequestEvent(source='assistant', models_usage=RequestUsage(prompt_tokens=362, completion_tokens=17), content=[FunctionCall(id='call_opch2ZMS86SkDU8L1MNal1hZ', arguments='{\"city\":\"Tokyo\"}', name='vacation_destinations')], type='ToolCallRequestEvent'), ToolCallExecutionEvent(source='assistant', models_usage=None, content=[FunctionExecutionResult(content=\"('Tokyo', 'Unavailable')\", call_id='call_opch2ZMS86SkDU8L1MNal1hZ')], type='ToolCallExecutionEvent')]\n",
      "source='assistant' models_usage=RequestUsage(prompt_tokens=352, completion_tokens=65) content=\"It looks like there are currently no available vacation options for Tokyo. However, if you're flexible about your destination or have any other places in mind, I can help you explore different travel options! Alternatively, I can provide information about Tokyo if you're planning a trip in the future. Just let me know how you'd like to proceed!\" type='TextMessage'\n"
     ]
    }
   ],
   "source": [
    "async def assistant_run() -> None:\n",
    "    response = await agent.on_messages(\n",
    "        [TextMessage(content=\"I would like to take a trip to Tokoyo\", source=\"user\")],\n",
    "        cancellation_token=CancellationToken(),\n",
    "    )\n",
    "    print(response.inner_messages)\n",
    "    print(response.chat_message)\n",
    "\n",
    "\n",
    "# Use asyncio.run(assistant_run()) when running in a script.\n",
    "await assistant_run()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".venv",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
